﻿package birdry.utils	{
	import com.greensock.TweenLite;
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;
	
	//	birdry.utils.MathUtil;
	
	
	public class TweenUtil	{
		
		private static var _eventDispatcherDic:Array = new Array();
		private static var _handlerDic:Array = new Array();
		
		
		// 배열에 추가한 요소 삭제처리 해야함!!!!!!!!!!!!!!!!!!!!
		
		
		
		public static function allKill(): void	{
			var max:uint = TweenUtil._eventDispatcherDic.length;
			for (var i:String in TweenUtil._eventDispatcherDic)	{
				var handler:Function = _handlerDic[i];
				if ( TweenUtil._eventDispatcherDic[i].hasEventListener( Event.ENTER_FRAME))	{
					TweenUtil._eventDispatcherDic[i].removeEventListener( Event.ENTER_FRAME, handler);
				}
			}
		}
		
		public static function kill( obj:* ): void	{
			var eventDispatcher:Sprite = TweenUtil._eventDispatcherDic[obj];
			var handler:Function = TweenUtil._handlerDic[obj];
			if (eventDispatcher)	{
				eventDispatcher.removeEventListener( Event.ENTER_FRAME, handler);
				eventDispatcher = null;
				delete TweenUtil._eventDispatcherDic[obj];
			}
		}
		
		public static function constant( obj:*, distance:uint, param:Object): void	{
			var paramMax:uint;
			var eventDispatcher:Sprite = TweenUtil._eventDispatcherDic[obj];
			var handler:Function = TweenUtil._handlerDic[obj];
			if (!eventDispatcher)	{
				eventDispatcher = new Sprite();
				TweenUtil._eventDispatcherDic[obj] = eventDispatcher;
				TweenUtil._handlerDic[obj] = onEnter;
			}	else		{
				if (eventDispatcher.hasEventListener(Event.ENTER_FRAME))		{
					eventDispatcher.removeEventListener( Event.ENTER_FRAME, handler);
				}
			}
			
			var tweenObj:Object = {};
			for (var i:String in param)	{
				if (param[i] is Function)		continue;
				if (obj[i] is Number)	{
					tweenObj[i] = param[i];
					paramMax++;
				}
			}
			eventDispatcher.addEventListener( Event.ENTER_FRAME, onEnter);
			function onEnter(e:Event):void 		{
				var paramCount:uint;
				for ( var i:String in tweenObj)	{
					if (Math.abs(obj[i] - tweenObj[i]) < Math.abs(distance))	{
						obj[i] = tweenObj[i];
						paramCount++
						if (paramCount == paramMax)	{
							onComplete();
							return;
						}
						continue;
					}
					obj[i] += ( obj[i] > tweenObj[i]) ? -distance : distance;
				}
				if (param.onProgress)	param.onProgress();
			}
			
			function onComplete(): void	{
				eventDispatcher.removeEventListener( Event.ENTER_FRAME, onEnter);
				eventDispatcher = null;
				delete TweenUtil._eventDispatcherDic[obj];
				
				if (param.onComplete)	param.onComplete();
			}
		}
		
	
		
	}	// class
}	// package